<template>
  <div class="approval-progress" v-loading="loading">
    <div class="progress-header">
      <div class="header-title">
        <span>审批进度</span>
        <el-tag
          v-if="approvalInfo"
          :type="getApprovalStatusType(approvalInfo.approvalStatus)"
          size="large"
        >
          {{ getApprovalStatusText(approvalInfo.approvalStatus) }}
        </el-tag>
      </div>
      <el-button
        v-if="!loading && approvalInfo"
        text
        icon="Refresh"
        @click="fetchApprovalDetail"
      >
        刷新
      </el-button>
    </div>

    <div v-if="!loading && approvalInfo" class="approval-timeline">
      <el-timeline>
        <el-timeline-item
          v-for="(node, index) in sortedNodes"
          :key="node.id"
          :timestamp="getNodeTimestamp(node)"
          :type="getNodeType(node)"
          :icon="getNodeIcon(node)"
          placement="top"
          size="large"
        >
          <div class="timeline-content">
            <div class="node-header">
              <div class="node-title-wrapper">
                <span class="node-title">{{ node.nodeName || `审批节点 ${index + 1}` }}</span>
                <el-tag
                  :type="getNodeStatusType(node.approvalStatus)"
                  size="small"
                >
                  {{ getNodeStatusText(node.approvalStatus) }}
                </el-tag>
              </div>
              <div class="node-type" v-if="approvalInfo.approvalType">
                {{ getApprovalTypeText(approvalInfo.approvalType) }}
              </div>
            </div>
            
            <div class="node-details">
              <div
                v-for="record in getNodeRecords(node.id)"
                :key="record.id"
                class="record-item"
              >
                <div class="record-main">
                  <div class="record-user">
                    <el-avatar
                      :size="40"
                      :style="{
                        backgroundColor: getAvatarColor(record.approvalUser?.userName),
                      }"
                    >
                      {{ getAvatarText(record.approvalUser?.nickName || record.approvalUser?.userName) }}
                    </el-avatar>
                    <div class="user-info">
                      <div class="user-name">
                        {{ record.approvalUser?.nickName || record.approvalUser?.userName || '未知' }}
                      </div>
                      <div class="user-dept">
                        {{ record.approvalUser?.deptName || '-' }}
                      </div>
                    </div>
                  </div>
                  <div class="record-status">
                    <el-tag
                      :type="getRecordStatusType(record.approvalStatus)"
                      size="small"
                    >
                      {{ getRecordStatusText(record.approvalStatus) }}
                    </el-tag>
                    <div class="record-time">
                      {{ record.createTime }}
                    </div>
                  </div>
                </div>
                <!-- 审批意见 -->
                <div
                  v-if="record.remark || record.approvalRemark"
                  class="record-remark"
                >
                  <div class="remark-label">审批意见：</div>
                  <div class="remark-content">
                    {{ record.remark || record.approvalRemark }}
                  </div>
                </div>
              </div>
              
              <!-- 如果该节点没有审批记录，显示待审批 -->
              <div
                v-if="getNodeRecords(node.id).length === 0"
                class="record-item pending"
              >
                <div class="record-user">
                  <el-avatar :size="40" style="background-color: #c0c4cc;">
                    待
                  </el-avatar>
                  <div class="user-info">
                    <div class="user-name">待审批</div>
                    <div class="user-dept">等待审批中...</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>

    <!-- 空状态 -->
    <el-empty
      v-if="!loading && !approvalInfo"
      description="暂无审批信息"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getApprovalDetail } from '@/api/approval'
import { approvalStatusMap, approvalStatusTypeMap, approvalTypeMap } from '@/utils/constant'

const props = defineProps({
  // 审批信息ID
  approvalInfoId: {
    type: [Number, String],
    required: true,
  },
})

// 加载状态
const loading = ref(false)

// 审批数据
const approvalInfo = ref(null)
const approvalNodes = ref([])
const approvalRecords = ref([])

// 排序后的节点列表
const sortedNodes = computed(() => {
  return [...approvalNodes.value].sort((a, b) => {
    return (a.approvalSort || 0) - (b.approvalSort || 0)
  })
})

// 获取审批详情
const fetchApprovalDetail = async () => {
  if (!props.approvalInfoId) {
    return
  }

  loading.value = true
  try {
    const res = await getApprovalDetail(props.approvalInfoId)
    if (res.code === 200 && res.data) {
      approvalInfo.value = res.data.approvalInfo
      approvalNodes.value = res.data.approvalNodes || []
      approvalRecords.value = res.data.approvalRecords || []
    } else {
      ElMessage.error(res.msg || '获取审批详情失败')
    }
  } catch (error) {
    console.error('获取审批详情失败:', error)
    ElMessage.error('获取审批详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取节点的审批记录
const getNodeRecords = (nodeId) => {
  return approvalRecords.value.filter(
    (record) => record.approvalNodeId === nodeId
  )
}

// 获取节点的时间戳
const getNodeTimestamp = (node) => {
  const records = getNodeRecords(node.id)
  if (records.length > 0) {
    return records[0].createTime || node.createTime
  }
  return node.createTime
}

// 获取节点类型（用于时间线样式）
const getNodeType = (node) => {
  if (node.approvalStatus === 'approved') {
    return 'success'
  } else if (node.approvalStatus === 'rejected') {
    return 'danger'
  } else {
    return 'primary'
  }
}

// 获取节点图标
const getNodeIcon = (node) => {
  if (node.approvalStatus === 'approved') {
    return 'CircleCheck'
  } else if (node.approvalStatus === 'rejected') {
    return 'CircleClose'
  } else {
    return 'Clock'
  }
}

// 获取审批状态文本
const getApprovalStatusText = (status) => {
  return approvalStatusMap[status] || status
}

// 获取审批状态类型
const getApprovalStatusType = (status) => {
  return approvalStatusTypeMap[status] || 'info'
}

// 获取审批类型文本
const getApprovalTypeText = (type) => {
  return approvalTypeMap[type] || type
}

// 获取节点状态文本
const getNodeStatusText = (status) => {
  return getApprovalStatusText(status)
}

// 获取节点状态类型
const getNodeStatusType = (status) => {
  return getApprovalStatusType(status)
}

// 获取记录状态文本
const getRecordStatusText = (status) => {
  return getApprovalStatusText(status)
}

// 获取记录状态类型
const getRecordStatusType = (status) => {
  return getApprovalStatusType(status)
}

// 获取头像文字
const getAvatarText = (name) => {
  if (!name) return '?'
  return name.length > 2 ? name.slice(-2) : name
}

// 获取头像颜色
const getAvatarColor = (name) => {
  if (!name) return '#409EFF'
  const colors = [
    '#409EFF',
    '#67C23A',
    '#E6A23C',
    '#F56C6C',
    '#909399',
    '#36CBCB',
    '#9C27B0',
  ]
  const index = name.charCodeAt(0) % colors.length
  return colors[index]
}

// 监听 approvalInfoId 变化
watch(
  () => props.approvalInfoId,
  (newVal) => {
    if (newVal) {
      fetchApprovalDetail()
    }
  },
  { immediate: true }
)
</script>

<style scoped lang="scss">
.approval-progress {
  padding: 20px;

  .progress-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;

    .header-title {
      display: flex;
      align-items: center;
      gap: 12px;

      span {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .approval-timeline {
    padding: 20px 0;

    :deep(.el-timeline) {
      padding-left: 0;
    }

    :deep(.el-timeline-item__timestamp) {
      font-size: 14px;
      color: #606266;
      font-weight: 500;
    }

    .timeline-content {
      background-color: #fff;
      border-radius: 8px;
      padding: 16px;
      margin-left: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
      }

      .node-header {
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid #ebeef5;

        .node-title-wrapper {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 8px;

          .node-title {
            font-size: 16px;
            font-weight: 600;
            color: #303133;
          }
        }

        .node-type {
          font-size: 12px;
          color: #909399;
        }
      }

      .node-details {
        .record-item {
          padding: 12px;
          margin-bottom: 12px;
          background-color: #f5f7fa;
          border-radius: 6px;
          transition: all 0.3s;

          &:last-child {
            margin-bottom: 0;
          }

          &:hover {
            background-color: #ecf5ff;
            transform: translateX(4px);
          }

          &.pending {
            background-color: #fdf6ec;
            border: 1px dashed #e6a23c;
          }

          .record-main {
            display: flex;
            justify-content: space-between;
            align-items: center;
          }

          .record-user {
            display: flex;
            align-items: center;
            flex: 1;

            .el-avatar {
              margin-right: 12px;
            }

            .user-info {
              flex: 1;

              .user-name {
                font-size: 14px;
                font-weight: 500;
                color: #303133;
                margin-bottom: 4px;
              }

              .user-dept {
                font-size: 12px;
                color: #909399;
              }
            }
          }

          .record-status {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 8px;

            .record-time {
              font-size: 12px;
              color: #909399;
            }
          }

          .record-remark {
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid #ebeef5;
            display: flex;
            .remark-label {
              font-size: 12px;
              line-height: 1.6;
              color: #909399;
              margin-bottom: 6px;
            }

            .remark-content {
              font-size: 12px;
              color: #606266;
              line-height: 1.6;
              word-break: break-word;
              white-space: pre-wrap;
            }
          }
        }
      }
    }
  }
}
</style>

